<template>
  <!--监控列表-->
  <div class="monitoring">
    <div class="monitoring-tab">
      <div
        :class="monitoringTab == 1 ? 'tab-select' : 'tab'"
        @click="monitoringTabSelect(1)"
      >
        监控中
      </div>
      <div
        :class="monitoringTab == 0 ? 'tab-select' : 'tab'"
        @click="monitoringTabSelect(0)"
      >
        已结束
      </div>
    </div>
    <div class="monitoring-search">
      <div class="monitoring-search-content-01">
        <el-input
          v-model="keyword"
          style="width: 300px"
          placeholder="请输入监控人姓名、身份证号、手机号查询"
        />
        <el-input
          v-model="vin"
          style="width: 300px"
          placeholder="请输入车架号查询"
        />
        <div>
          风险等级：
          <el-select
            v-model="riskLevel"
            placeholder="请输入风险等级"
            style="width: 100px"
          >
            <el-option label="全部" :value="-1" />
            <el-option label="高风险" :value="3" />
            <el-option label="中风险" :value="2" />
            <el-option label="低风险" :value="1" />
          </el-select>
        </div>

        <el-button @click="reset">重置</el-button>
        <el-button
          color="rgb(222, 41, 16)"
          style="margin-left: -10px"
          type="primary"
          @click="pageList"
          >查询</el-button
        >
      </div>
      <el-divider />
      <div class="monitoring-search-content-02">
        <span style="font-weight: 700; font-size: 14px; line-height: 40px"
          >下单日期：</span
        >
        <el-radio-group v-model="happenDate">
          <el-radio :value="1">今日</el-radio>
          <el-radio :value="2">近七日</el-radio>
          <el-radio :value="3">近30日</el-radio>
          <el-radio :value="4">自定义</el-radio>
        </el-radio-group>
        <div class="date-picker" v-if="happenDate == 4">
          <el-date-picker
            v-model="customizeDate"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </div>
      </div>
    </div>
    <div class="monitoring-admin-table">
      <div class="table-header">
        <div class="header-tip">
          总计
          <span class="header-tip-nember">{{
            monitoringList?.total || 0
          }}</span>
          个监控对象
        </div>
        <div class="header-tip-botton">
          <el-button
            type="primary"
            @click="addMonitoring"
            color="rgb(222, 41, 16)"
            v-if="permissionState.update"
            ><el-icon><Plus /></el-icon>新增监控</el-button
          >
          <el-button
            color="rgb(222, 41, 16)"
            type="primary"
            @click="exportAsset"
            v-if="permissionState.export"
            >导出excel</el-button
          >
        </div>
      </div>
      <div style="padding: 10px">
        <el-table
          :data="monitoringList?.list"
          stripe
          border
          :header-cell-style="tableHeaderColor"
          :cell-style="cellStyle"
          max-height="400"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="identifier" label="资产编号" width="180" />
          <el-table-column prop="businessType" label="业务类型" width="180" />
          <el-table-column prop="vin" label="车架号" width="180" />
          <el-table-column
            prop="newRiskTimeParse"
            label="最新风险时间"
            width="180"
          />
          <el-table-column label="风险等级" width="180">
            <template #default="scoped">
              <div style="display: flex; gap: 10px; justify-content: center">
                <div style="color: rgb(217, 0, 27)">
                  高：{{ scoped.row.highRisk }}
                </div>
                <div style="color: rgb(247, 178, 77)">
                  中：{{ scoped.row.mediumRisk }}
                </div>
                <div style="color: rgb(222, 216, 123)">
                  低：{{ scoped.row.lowRisk }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="monitorState" label="监控状态" width="180" />
          <el-table-column prop="orgName" label="所属机构" width="180" />
          <el-table-column prop="productName" label="产品名称" width="180" />
          <el-table-column prop="createdAtParse" label="监控时间" width="180" />
          <el-table-column fixed="right" label="操作" min-width="180">
            <template #default="scoped">
              <el-button
                v-if="scoped.row.monitorState === '监控中'"
                link
                type="primary"
                size="small"
                @click="stopMonitor(scoped.row.id)"
                ><span style="color: rgb(222, 41, 16)"
                  >结束监控</span
                ></el-button
              >
              <el-button
                link
                type="primary"
                size="small"
                @click="searchMonitorReport(scoped.row.identifier)"
                ><span style="color: rgb(222, 41, 16)">查看</span></el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="monitoring-pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="monitoringList?.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router"; // 引入useRouter函数
import { Plus } from "@element-plus/icons-vue";
import http from "@/request/request";
import { Data } from "@/request/pageData";
import { Permission } from "@/util/LocalStorgeGetPermission";

const router = useRouter(); // 获取路由实例
interface MonitoringAsset {
  id: number;
  identifier: string;
  businessType: string;
  vin: string;
  newRiskTimeParse: string;
  lowRisk: number;
  mediumRisk: number;
  highRisk: number;
  monitorState: string;
  orgName: string;
  spName: string;
  productName: string;
  createdAtParse: string;
}
//--------------------------------------------------变量--------------------------//

// table样式
const tableHeaderColor = {
  background: "rgb(245, 248, 250) !important",
  color: "rgb(51, 51, 51)",
  "text-align": "center",
};
const cellStyle = {
  "text-align": "center",
};
const monitoringTab = ref(1);
const keyword = ref("");
const vin = ref("");
const happenDate = ref<number>(1); // 发生日期
const customizeDate = ref([]); // 自定义日期
const riskLevel = ref<number>(-1);
const spName = ref<string>("");
// 分页
const currentPage = ref(1);
const pageSize = ref(10);
// 监控列表数据
const monitoringList = ref<Data<MonitoringAsset>>();

// 选择框
const multipleSelection = ref<number[]>([]);
// 权限
const permissionState = ref({
  insert: false,
  update: false,
  delete: false,
  export: false,
  imports: false,
});
//--------------------------------------------------方法--------------------------//
const monitoringTabSelect = (state: number) => {
  monitoringTab.value = state;
  pageList();
};
// 重置
const reset = () => {
  keyword.value = "";
  vin.value = "";
  riskLevel.value = -1;
  spName.value = "";
};

// 分页函数
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  pageList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  pageList();
};
// 查看报告
const searchMonitorReport = (id: string) => {
  const url = router.resolve({
    path: "/monitoringAssetIno?id=" + id,
    query: {
      id: id,
    },
  });
  window.open(url.href, "_blank");
};
// 贷中新增跳转
const addMonitoring = () => {
  router.push("/monitoringAdd");
};
// 分页查询
const pageList = async () => {
  let happenStartDate = null;
  let happenEndDate = null;
  if (happenDate.value === 4) {
    happenStartDate = customizeDate.value[0] + " 00:00:00";
    happenEndDate = customizeDate.value[1] + " 23:59:59";
  }

  const params = {
    page: currentPage.value,
    pageSize: pageSize.value,
    keyWord: keyword.value,
    vin: vin.value,
    happenDate: happenDate.value,
    happenStartDate,
    happenEndDate,
    riskLevel: riskLevel.value == -1 ? null : riskLevel.value,
    monitorState: monitoringTab.value,
  };
  try {
    const { data } = await http.get<Data<MonitoringAsset>>(
      "/api/after-loan/list",
      params
    );
    monitoringList.value = data;
  } catch (err) {
    console.log(err);
  }
};

// 结束监控
const stopMonitor = async (id: number) => {
  try {
    await http.get("/api/after-loan/endMonitoring", { id });
    pageList();
  } catch (err) {
    console.log(err);
  }
};
// 批量选择
const handleSelectionChange = (val: MonitoringAsset[]) => {
  multipleSelection.value = val.map((m) => m.id);
};
// 批量导出
const exportAsset = async () => {
  let happenStartDate = null;
  let happenEndDate = null;
  if (happenDate.value === 4) {
    happenStartDate = customizeDate.value[0] + " 00:00:00";
    happenEndDate = customizeDate.value[1] + " 23:59:59";
  }

  const params = {
    page: currentPage.value,
    pageSize: pageSize.value,
    keyWord: keyword.value,
    vin: vin.value,
    happenDate: happenDate.value,
    happenStartDate,
    happenEndDate,
    riskLevel: riskLevel.value == -1 ? null : riskLevel.value,
    monitorState: monitoringTab.value,
    spName: spName.value,
    ids: multipleSelection.value,
  };
  try {
    const { data } = await http.get<string>("/api/after-loan/export", params);
    const link = document.createElement("a");
    link.href = data;
    link.download = "金额目标比例";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(data);
  } catch (err) {
    console.log(err);
  }
};
//-----------------------------------------------生命周期-------------------------//
onMounted(() => {
  const p = new Permission("/monitoring").getPermission();
  if (!p) {
    router.push("/");
  } else {
    permissionState.value = p;
    pageList();
  }
});
</script>

<style lang="less" scoped>
.monitoring {
  width: 100%;
  height: 100%;
  .monitoring-tab {
    display: flex;
    .tab {
      width: 150px;
      height: 32px;
      background-color: rgb(255, 255, 255);
      color: rgb(222, 41, 16);
      line-height: 36px;
      border-top-left-radius: 6px;
      border-top-right-radius: 6px;
      border: 1px solid rgb(222, 41, 16);
    }
    .tab-select {
      width: 150px;
      height: 32px;

      background-color: rgb(222, 41, 16);
      color: rgb(255, 255, 255);
      line-height: 36px;
      border-top-left-radius: 6px;
      border-top-right-radius: 6px;
      border: 1px solid rgb(222, 41, 16);
    }
  }
  .monitoring-search {
    width: 100%;
    height: 17%;
    background-color: rgb(255, 255, 255);
    .monitoring-search-content-01 {
      display: flex;
      gap: 20px;
      padding-top: 10px;
      padding-left: 10px;
    }
    .monitoring-search-content-02 {
      display: flex;
      gap: 20px;
      padding-left: 10px;
      .date-picker {
        align-self: center;
        width: 300px;
        .el-date-picker {
          width: 100%;
        }
      }
      .monitoring-serach-item-01 {
        margin-top: 10px;
      }
    }
  }
  .monitoring-admin-table {
    margin-top: 1%;
    height: 78%;
    width: 100%;
    background-color: rgb(255, 255, 255);
    .table-header {
      padding-left: 20px;
      padding-top: 10px;
      display: flex;
      .header-tip {
        width: 8%;
        .header-tip-nember {
          color: rgb(64, 158, 255);
        }
      }
      .header-tip-botton {
        width: 91.5%;
        display: flex;
        justify-content: end;
      }
    }
    .monitoring-pagination {
      position: absolute;
      right: 2%;
      bottom: 4%;
    }
  }
}
.el-divider--horizontal {
  margin-top: 20px;
  margin-bottom: 10px;
}
</style>